package com.scj.vue3springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scj.vue3springboot.entity.SysMenu;
import com.scj.vue3springboot.entity.vo.MenuVo;
import com.scj.vue3springboot.enums.StatusEnum;
import com.scj.vue3springboot.service.SysMenuService;
import com.scj.vue3springboot.mapper.SysMenuMapper;
import com.scj.vue3springboot.util.DateUtil;
import com.scj.vue3springboot.util.JwtUtils;
import com.scj.vue3springboot.util.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 86182
 * @description 针对表【sys_menu(菜单权限表)】的数据库操作Service实现
 * @createDate 2023-10-11 11:09:08
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
        implements SysMenuService {

    @Override
    public Result findAllMenu() {
        List<MenuVo> list = baseMapper.findAllMenu();

        // 使用 Stream 对 list 进行转换
        List<MenuVo> topLevelMenus = list.stream()
                .filter(menu -> menu.getParentId() == 0)
                .map(menu -> addChildMenus(menu, list))
                .collect(Collectors.toList());
        return Result.success("查询成功", topLevelMenus);
    }

    private MenuVo addChildMenus(MenuVo parent, List<MenuVo> allMenus) {
        List<MenuVo> children = allMenus.stream()
                .filter(menu -> menu.getParentId() != null && menu.getParentId().equals(parent.getMenuId()))
                .map(menu -> addChildMenus(menu, allMenus))
                .collect(Collectors.toList());

        parent.setChildren(children);
        return parent;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addMenu(SysMenu sysMenu, String token) {
        // 通过token获取用户id
        Long tokenUserId= Long.valueOf(JwtUtils.validateJWT(token).getClaims().getId());
        String date = DateUtil.getNowDate();

        sysMenu.setCreateBy(tokenUserId);
        sysMenu.setCreateTime(date);
        sysMenu.setUpdateBy(tokenUserId);
        sysMenu.setUpdateTime(date);

        baseMapper.insert(sysMenu);
        return Result.success("添加成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateMenu(SysMenu sysMenu, String token) {
        // 通过token获取用户id
        Long tokenUserId= Long.valueOf(JwtUtils.validateJWT(token).getClaims().getId());
        String date = DateUtil.getNowDate();

        sysMenu.setUpdateBy(tokenUserId);
        sysMenu.setUpdateTime(date);

        baseMapper.updateById(sysMenu);
        return Result.success("修改成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteMenu(Long menuId, String token) {
        // 通过token获取用户id
        Long tokenUserId = Long.valueOf(JwtUtils.validateJWT(token).getClaims().getId());
        String nowDate = DateUtil.getNowDate();

        // 通过菜单ID查询菜单信息
        SysMenu sysMenu = baseMapper.selectById(menuId);
        if (sysMenu == null) {
            return Result.failure("菜单不存在");
        }

        //判断这个菜单的类型
        switch (sysMenu.getMenuType()) {
            case "M":
                //如果是目录类型，那么就查询是否有子菜单
                List<Object> menuList = baseMapper.selectObjs(
                        new QueryWrapper<>(new SysMenu())
                        .eq("parent_id", menuId)
                        .eq("menu_type", "C"));
                //判断是否为空，如果不为空，就查询按钮
                if (!menuList.isEmpty()) {
                    List<Object> buttonList = baseMapper.selectObjs(
                            new QueryWrapper<>(new SysMenu())
                                    .in("parent_id", menuList)
                                    .eq("menu_type", "F"));
                    //判断按钮是否为空，如果不为空，就删除按钮
                    if (!buttonList.isEmpty()) {
                        baseMapper.update(null,
                                new UpdateWrapper<>(new SysMenu())
                                        .set("status", StatusEnum.DISABLE.getCode())
                                        .set("update_by", tokenUserId)
                                        .set("update_time", nowDate)
                                        .in("menu_id", buttonList));
                    }
                    baseMapper.update(null,
                            new UpdateWrapper<>(new SysMenu())
                                    .set("status", StatusEnum.DISABLE.getCode())
                                    .set("update_by", tokenUserId)
                                    .set("update_time", nowDate)
                                    .in("menu_id", menuList));
                }
                //删除目录
                baseMapper.update(null,
                        new UpdateWrapper<>(new SysMenu())
                                .set("status", StatusEnum.DISABLE.getCode())
                                .set("update_by", tokenUserId)
                                .set("update_time", nowDate)
                                .eq("menu_id", menuId));

                break;
            case "C":
                //如果是菜单类型，那么就查询是否有按钮
                List<Object> buttonList = baseMapper.selectObjs(
                        new QueryWrapper<>(new SysMenu())
                                .eq("parent_id", menuId)
                                .eq("menu_type", "F"));
                //判断按钮是否为空，如果不为空，就删除按钮
                if (!buttonList.isEmpty()) {
                    baseMapper.update(null,
                            new UpdateWrapper<>(new SysMenu())
                                    .set("status", StatusEnum.DISABLE.getCode())
                                    .set("update_by", tokenUserId)
                                    .set("update_time", nowDate)
                                    .in("menu_id", buttonList));
                }
                //删除菜单
                baseMapper.update(null,
                        new UpdateWrapper<>(new SysMenu())
                                .set("status", StatusEnum.DISABLE.getCode())
                                .set("update_by", tokenUserId)
                                .set("update_time", nowDate)
                                .eq("menu_id", menuId));
                break;
            case "F":
                //如果是按钮类型，那么就删除按钮
                baseMapper.update(null,
                        new UpdateWrapper<>(new SysMenu())
                                .set("status", StatusEnum.DISABLE.getCode())
                                .set("update_by", tokenUserId)
                                .set("update_time", nowDate)
                                .eq("menu_id", menuId));
                break;
            default:
                return Result.failure("不支持的菜单类型");
        }
        return Result.success("删除成功");
    }
}




